// 项目管理页面JavaScript功能

// 全局变量
let currentProjects = [];

// DOM元素
const elements = {
    projectContainer: null,
    loadingSpinner: null,
    emptyState: null,
    addProjectModal: null,
    successToast: null,
    errorToast: null
};

// 页面初始化
document.addEventListener('DOMContentLoaded', function() {
    initializeElements();
    initializeEventListeners();

    loadProjects();
});

// 初始化DOM元素
function initializeElements() {
    elements.projectContainer = document.getElementById('projectContainer');
    elements.loadingSpinner = document.getElementById('loadingSpinner');
    elements.emptyState = document.getElementById('emptyState');
    elements.addProjectModal = document.getElementById('addProjectModal');
    elements.successToast = document.getElementById('successToast');
    elements.errorToast = document.getElementById('errorToast');
}

// 初始化事件监听器
function initializeEventListeners() {
    // 保存按钮事件
    document.getElementById('saveProjectBtn')?.addEventListener('click', handleCreateProject);
}

// 加载项目列表
async function loadProjects() {
    try {
        showLoading();
        
        const response = await fetch('/api/projects');
        if (!response.ok) {
            throw new Error('加载项目列表失败');
        }
        
        currentProjects = await response.json();
        renderProjects();
        
    } catch (error) {
        console.error('加载项目失败:', error);
        showMessage('加载项目列表失败: ' + error.message, 'error');
    } finally {
        hideLoading();
    }
}



// 渲染项目列表
function renderProjects() {
    if (!elements.projectContainer) return;
    
    if (currentProjects.length === 0) {
        elements.projectContainer.innerHTML = '';
        elements.emptyState.style.display = 'block';
        return;
    }
    
    elements.emptyState.style.display = 'none';
    
    elements.projectContainer.innerHTML = currentProjects.map(project => `
        <div class="col-lg-4 col-md-6 col-sm-12 mb-4">
            <div class="card project-card shadow-sm border-0 h-100">
                <div class="card-header bg-white border-bottom-0 py-3">
                    <div class="d-flex align-items-center">
                        <div class="bg-primary bg-opacity-10 rounded-circle p-2 me-3">
                            <i class="bi bi-folder text-primary"></i>
                        </div>
                        <h6 class="card-title mb-0 fw-bold text-dark">${escapeHtml(project.name)}</h6>
                    </div>
                </div>
                <div class="card-body py-3">
                    <p class="card-text text-muted mb-0 lh-base">${escapeHtml(project.description || '暂无描述')}</p>
                </div>
                <div class="card-footer bg-light border-top-0 py-3">
                    <div class="d-flex justify-content-between align-items-center">
                        <small class="text-muted">
                            <i class="bi bi-calendar3 me-1"></i>
                            ${formatDate(project.createdAt)}
                        </small>
                        <button type="button" class="btn btn-outline-danger btn-sm px-3" onclick="deleteProject('${project.id}')">
                            <i class="bi bi-trash me-1"></i>删除
                        </button>
                    </div>
                </div>
            </div>
        </div>
    `).join('');
}







// 显示创建项目模态框
function showCreateModal() {
    // 清空表单字段
    document.getElementById('projectName').value = '';
    document.getElementById('projectDescription').value = '';
    
    showModal(elements.addProjectModal);
}

// 处理创建项目
async function handleCreateProject(e) {
    e.preventDefault();
    
    // 直接从表单元素获取数据
    const projectName = document.getElementById('projectName').value.trim();
    const projectDescription = document.getElementById('projectDescription').value.trim();
    
    // 验证必填字段
    if (!projectName) {
        showMessage('请输入项目名称', 'error');
        return;
    }
    
    const projectData = {
        name: projectName,
        description: projectDescription,
        managerId: 'D20240001' // 默认项目经理ID
    };
    
    try {
        showLoading();
        
        const response = await fetch('/api/projects', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(projectData)
        });
        
        if (!response.ok) {
            const error = await response.text();
            throw new Error(error || '创建项目失败');
        }
        
        // 清空表单
        document.getElementById('projectName').value = '';
        document.getElementById('projectDescription').value = '';
        
        hideModal(elements.addProjectModal);
        showMessage('项目创建成功', 'success');
        loadProjects();
        
    } catch (error) {
        console.error('创建项目失败:', error);
        showMessage('创建项目失败: ' + error.message, 'error');
    } finally {
        hideLoading();
    }
}



// 删除项目
async function deleteProject(projectId) {
    if (!confirm('确定要删除这个项目吗？此操作不可恢复。')) {
        return;
    }
    
    try {
        showLoading();
        
        const response = await fetch(`/api/projects/${projectId}`, {
            method: 'DELETE'
        });
        
        if (!response.ok) {
            const error = await response.text();
            throw new Error(error || '删除项目失败');
        }
        
        showMessage('项目删除成功', 'success');
        loadProjects();
        
    } catch (error) {
        console.error('删除项目失败:', error);
        showMessage('删除项目失败: ' + error.message, 'error');
    } finally {
        hideLoading();
    }
}

// 显示模态框
function showModal(modal) {
    if (modal) {
        const bootstrapModal = new bootstrap.Modal(modal);
        bootstrapModal.show();
    }
}

// 隐藏模态框
function hideModal(modal) {
    if (modal) {
        const bootstrapModal = bootstrap.Modal.getInstance(modal);
        if (bootstrapModal) {
            bootstrapModal.hide();
        }
    }
}

// 显示加载指示器
function showLoading() {
    if (elements.loadingSpinner) {
        elements.loadingSpinner.style.display = 'flex';
    }
}

// 隐藏加载指示器
function hideLoading() {
    if (elements.loadingSpinner) {
        elements.loadingSpinner.style.display = 'none';
    }
}

// 显示消息
function showMessage(message, type = 'info') {
    const toastElement = type === 'error' ? elements.errorToast : elements.successToast;
    if (toastElement) {
        const toastBody = toastElement.querySelector('.toast-body');
        if (toastBody) {
            toastBody.textContent = message;
        }
        const toast = new bootstrap.Toast(toastElement);
        toast.show();
    }
}

// 工具函数
function escapeHtml(text) {
    const div = document.createElement('div');
    div.textContent = text;
    return div.innerHTML;
}

function formatDate(dateString) {
    if (!dateString) return '';
    const date = new Date(dateString);
    return date.toLocaleDateString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit'
    });
}

// 导出函数供全局使用
window.deleteProject = deleteProject;
window.showCreateModal = showCreateModal;